package com.qdlc.p2p.common.core.queue.queue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;

import org.springframework.context.ApplicationContext;

import com.qdlc.p2p.common.core.queue.AbstractQueueHandler;
import com.qdlc.p2p.common.core.queue.QueueHandlers;
import com.qdlc.p2p.common.core.queue.ValueEvent;


/**
 * 使用阻塞队列LinkedBlockingQueue实现队列处理。
 * @author linya 2015-12-31
 */
public class ConcurrentQueueHandler extends AbstractQueueHandler {

	private BlockingQueue<ValueEvent> eventQueue = new LinkedBlockingQueue<ValueEvent>();
	
	@Override
	public void put0(ValueEvent event) {
		try {
			eventQueue.put(event);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Future<ValueEvent> submit(ValueEvent event) {
		Future<ValueEvent> future = scheduledTask(new Tasker(event));
		return future;
	}
	
	@Override
	public List<Future<ValueEvent>> submit(Collection<? extends ValueEvent> events) {
		List<Future<ValueEvent>> futureList = new ArrayList<Future<ValueEvent>>();
		for(ValueEvent event: events){
			futureList.add(submit(event));
		}
		return futureList;
	}

	@Override
	protected boolean isEmpty() {
		return eventQueue.isEmpty();
	}

	@Override
	protected void doRun() {
		ValueEvent event = eventQueue.poll();
		if(event != null){
			submit(event);
		}
	}
	
	/**
	 * 执行ITaskProcessor接口
	 * @author linya 2015-12-28
	 */
	private class Tasker implements EventTasker{
		final ValueEvent event;
		Tasker(ValueEvent event){
			this.event = event;
		}
		@Override
		public ValueEvent call() throws Exception {
			process(event);
			return event;
		}
		@Override
		public ValueEvent getValueEvent() {
			return event;
		}
	}

	@Override
	protected void postApplicationContext(ApplicationContext context) {
		QueueHandlers.initPostAppliactionContext(context);
	}

}
